$(function () {
    function PMNeedPayBill() {
        // 表格ID
        this.dataTable = $("#dataTable");
        // 按钮
        this.$seachr_btn = $('#btn_search');
        this.$btn_search_clear = $('#btn_search_clear');
        this.importBtn = $('#importBtn');
        this.startImportBtn = $('#start-import-btn');
        this.deleteBtn = $('#deleteBtn');
        // moda;
        this.importModal = $('#import-modal');
        // 初始化
        this.init();
    }

    PMNeedPayBill.prototype.Constructor = PMNeedPayBill;

    PMNeedPayBill.prototype.init = function () {
        this.loadTable();
        this.registEvent();
    };

    PMNeedPayBill.prototype.loadTable = function () {
        this.dataTable.dataTable({
            "sAjaxSource": "/pmbill/needpay/page",
            "aoColumns": [
                {
                    "sWidth": "5%",
                    "sTitle": "<input type=\"checkbox\" class=\"ace\" /><span class=\"lbl\"></span>",
                    "sClass": "center",
                    "mData": "id",
                    "bSortable": false
                },
                {"sWidth": "8%", "sTitle": "房号", "sClass": "center", "mData": "houseNumber", "bSortable": false},
                {"sWidth": "8%", "sTitle": "住户", "sClass": "center", "mData": "userName", "bSortable": false},
                {"sWidth": "10%", "sTitle": "住户手机号", "sClass": "center", "mData": "userMobile", "bSortable": false},
                {"sWidth": "10%", "sTitle": "费用时间", "sClass": "center", "mData": "duration", "bSortable": false},
                {"sWidth": "8%", "sTitle": "账单金额", "sClass": "center", "mData": "totalAmount", "bSortable": false},
                {"sWidth": "12%", "sTitle": "出账时间", "sClass": "center", "mData": "releaseTime", "bSortable": false},
                {"sWidth": "8%", "sTitle": "是否下发", "sClass": "center", "mData": "published", "bSortable": false},
                // {"sWidth": "12%", "sTitle": "下发时间", "sClass": "center", "mData": "publishTime", "bSortable": false},
                {"sWidth": "12%", "sTitle": "创建时间", "sClass": "center", "mData": "created", "bSortable": false},
                {"sWidth": "10%", "sTitle": "操作", "sClass": "center", "mData": "id", "bSortable": false}
            ],
            "aLengthMenu": [10, 30, 50],
            "aaSorting": [],
            "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                var id = aData["id"];
                var inputHtml = "<input type='checkbox' class='ace' name='teacherId' value='" + id + "'/><span class=\"lbl\"></span>";
                $('td:eq(0)', nRow).html(inputHtml);

                if (aData['releaseTime']) {
                    $('td:eq(6)', nRow).html(SysTool.Date.formatDate(aData['releaseTime'], 'yyyy-MM-dd'));
                }
                var published = aData['published'];
                if (published) {
                    $('td:eq(7)', nRow).html('<span class="label label-success">是</span>');
                    var publishTime = aData['publishTime'];
                    // if (publishTime) {
                    //     $('td:eq(7)', nRow).html(SysTool.Date.formatDate(aData['created'], 'yyyy-MM-dd'));
                    // }
                } else {
                    $('td:eq(7)', nRow).html('');
                }
                if (aData['created']) {
                    $('td:eq(8)', nRow).html(SysTool.Date.formatDate(aData['created'], 'yyyy-MM-dd'));
                }
                // 操作
                var option = '<a title="账单明细" href="/pmbill/needpay/detail/' + id + '" class="btn btn-xs btn-info">明细</a>&nbsp;';
                if (!published) {
                    option += '<a title="下发订单给用户" billid="' + id + '" href="javascript:void(0)" class="btn btn-xs btn-success">下发</a>';
                }
                option += '<a title="删除订单" billid="' + id + '" href="javascript:void(0)" class="btn btn-xs btn-danger">删除</a>';
                $('td:eq(9)', nRow).html(option);
            },
            "fnServerParams": function (aoData) {
                queryCondition("#search-form", aoData);
            },
            "fnStateLoaded": function (oSettings, oData) {
//                alert(JSON.stringify(oData));
            }
        });

        function queryCondition(queryFormId, aoData) {
            var queryParameters = $(queryFormId).serializeArray();
            $(queryParameters).each(function (i, v) {
                aoData.push(v);
            });
        }
    };

    PMNeedPayBill.prototype.refreshTable = function () {
        this.dataTable.dataTable().fnClearTable();
    };

    PMNeedPayBill.prototype.registEvent = function () {
        var that = this;

        this.deleteBtn.on('click', function () {
            var ck = that.dataTable.find("tbody input:checked");
            if (!ck || ck.length === 0) {
                BootBox.warning('请选择需要删除的账单！');
                return false;
            }
            var ids = ck.map(function (i, v) {
                return $(this).val();
            }).get().join(",");
            BootBox.confirm('即将删除所选择的账单，确定继续？', function (b) {
                if (!b) return;
                SysTool.Ajax.ajaxJsonCall('pmbill/needpay/del', {ids: ids}, function (data) {
                    that.$seachr_btn.click();
                });
            });
        });

        that.dataTable.on('click', 'a.btn-danger', function () {
            var $that = $(this);
            BootBox.confirm('确定删除当前账单？', function (b) {
                if (!b) return;
                var ids = $that.attr('billid');
                SysTool.Ajax.ajaxJsonCall('pmbill/needpay/delete/' + ids, {}, function (data) {
                    that.$seachr_btn.click();
                });
            });
        });
        that.dataTable.on('click', 'a.btn-success', function () {
            var $that = $(this);
            BootBox.confirm('确定下发当前账单？', function (b) {
                if (!b) return;
                var ids = $that.attr('billid');
                SysTool.Ajax.ajaxJsonCall('pmbill/needpay/publish/' + ids, {}, function (data) {
                    that.$seachr_btn.click();
                });
            });
        });
        that.$seachr_btn.click(function () {
            var oSettings = that.dataTable.dataTable().fnSettings();
            oSettings._iDisplayStart = 0;
            that.dataTable.dataTable().fnClearTable();
        });

        that.$btn_search_clear.click(function () {
            $('#liveUserName').val('');
            $('#liveUserMobile').val('');
            $('#houseNumber').val('');
            $('#releaseStartTime').val('');
            $('#releaseEndTime').val('');
            that.$seachr_btn.click();
        });

        that.importBtn.click(function () {
            that.importModal.modal('show');
        });

        $('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
            //$(this).prev().focus();
        });

        $('#excel-input-file').ace_file_input({
            no_file: '未选择文件...',
            btn_choose: '选择',
            btn_change: '修改',
            droppable: false,
            thumbnail: false,//| true | large
            whitelist: 'xls|xlsx',
            // blacklist:'png|jpeg',
            before_change: function (files, dropped) {
                var allowed_files = [];
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    if (typeof file === "string") {
                        //IE8 and browsers that don't support File Object
                        if (!(/\.(xls|xlsx)$/i).test(file)) return false;
                    } else {
                        var type = $.trim(file.type);
                        if (( type.length > 0 && !(/office/).test(type))
                            || ( type.length == 0 && !(/\.(xls|xlsx)$/i).test(file.name) )
                        ) {
                            BootBox.warning("文件格式不正确，请上传excel格式的文件！");
                            continue;
                        }
                    }
                    var size = file.size;

                    if (size > 5120000) {
                        BootBox.warning('文件大小超过限制，不能超过' + (5120000 / 1024) + 'KB.');
                        return false;
                    }
                    allowed_files.push(file);
                }
                if (allowed_files.length == 0) return false;
                return allowed_files;
            },
        });

        that.startImportBtn.click(function () {
            var f = $('#excel-input-file').val();
            if (!f) {
                BootBox.warning('请选择导入文件');
                return false;
            }
            that.startImportBtn.text('导入中...');
            that.startImportBtn.attr('disabled', true);
            SysTool.Ajax.ajaxSubmitForm(that.importModal.find('form'), function (data) {
                that.startImportBtn.removeAttr('disabled');
                that.startImportBtn.text('导入');
                that.importModal.modal('hide');
                if (data.hasError) {
                    BootBox.success('数据导入完成，部分数据导入失败，请检查必填字段是否为空，格式是否正确！');
                    var msg = "注意：某些数据导入失败，请检查数据是否为空或格式是否正确，修改后再次尝试导入!失败行数：" + data.failedRowCnt + ", 失败行号：" + data.failedRowNumber;
                    $('#error-info').html(msg);
                    $('.alert-danger').removeClass('hide');
                } else {
                    BootBox.success('数据全部导入成功！');
                }
                that.refreshTable();
                $('.ace-file-input .icon-remove').click();
            });
        });

        SysTool.Html.bindEnterClick([], that.$seachr_btn);
    };

    window.PMNeedPayBill = new PMNeedPayBill();
});